package org.smart4j.chapter1.helper;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.chapter1.utils.CollectionUtil;
import org.smart4j.chapter1.utils.PropsUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 数据库操作助手
 *
 * @author LG93
 * @create 2017-08-10 17:43
 **/
@SuppressWarnings("UnusedAssignment")
public class DataBaseHelper {
    private static final Logger logger = LoggerFactory.getLogger(DataBaseHelper.class);

    /**
     * 本地线程变量，存储conn
     * 线程安全：保证一个线程一连接
     */
    private static final ThreadLocal<Connection> CONNECTION_HOLDER;

    /**
     * 用于封装jdbc
     * 提供query、方法
     */
    private static final QueryRunner QUERY_RUNNER ;

    /**
     * 数据库连接池，提高系统性能，减少数据库频繁连接
     */
    private static final BasicDataSource DATA_SOURCE;

    private static final String DRIVER;

    private static final String URL;

    private static final String USERNAME;

    private static final String PASSWORD;

    static {

        CONNECTION_HOLDER = new ThreadLocal<>();
        QUERY_RUNNER = new QueryRunner();

        System.out.println("==> 测试");

        Properties conf = PropsUtils.loadProperties("config.properties");
        DRIVER = conf.getProperty("jdbc.driver");
        URL = conf.getProperty("jdbc.url");
        USERNAME = conf.getProperty("jdbc.username");
        PASSWORD = conf.getProperty("jdbc.password");

        /**
         * 初始化连接池
         */
        DATA_SOURCE = new BasicDataSource();
        DATA_SOURCE.setDriverClassName(DRIVER);
        DATA_SOURCE.setUrl(URL);
        DATA_SOURCE.setUsername(USERNAME);
        DATA_SOURCE.setPassword(PASSWORD);
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            logger.debug("can not load jdbc driver", e);
        }
    }

    /**
     *  执行sql文件
     * @param filePath
     */
    public static void executeSqlFile(String filePath) {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String sql;
        try {
            while ((sql = br.readLine()) != null) {
                DataBaseHelper.excuteUpdate(sql);
            }
        } catch (IOException e) {
            logger.error("execute sql file failure ", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询实体列表
     *
     * @param entityClass
     * @param sql
     * @param params
     * @param <T>
     * @return
     */
    public static <T> List<T> queryEntityList(Class<T> entityClass, String sql, Object... params) {
        List<T> entityList;
        try {
            Connection conn = getConnection();
            entityList = QUERY_RUNNER.query(conn, sql, new BeanListHandler<T>(entityClass), params);
        } catch (SQLException e) {
            logger.error("query entity list failure", e);
            throw new RuntimeException(e);
        }
        return entityList;
    }

    /**
     * 查询单个实体
     *
     * @param entityClass
     * @param sql
     * @param params
     * @param <T>
     * @return
     */
    public static <T> T queryEntity(Class<T> entityClass, String sql, Object... params) {
        T entity;
        try {
            Connection conn = getConnection();
            entity = QUERY_RUNNER.query(conn, sql, new BeanHandler<T>(entityClass), params);
        } catch (SQLException e) {
            logger.error("query entity failure", e);
            throw new RuntimeException(e);
        }
        return entity;
    }

    /**
     * 执行多表连接查询
     *
     * @param sql
     * @param params
     * @return
     */
    public static List<Map<String, Object>> executeQuery(String sql, Object... params) {
        List<Map<String, Object>> resutl;
        Connection conn = getConnection();
        try {
            resutl = QUERY_RUNNER.query(conn, sql, new MapListHandler(), params);
        } catch (SQLException e) {
            logger.error("executeQuery mapList failure", e);
            throw new RuntimeException(e);
        }
        return resutl;
    }

    /**
     * 执行更新语句
     *
     * @param sql
     * @param params
     * @return
     */
    public static int excuteUpdate(String sql, Object... params) {
        int rows;
        Connection conn = getConnection();
        try {
            rows = QUERY_RUNNER.update(conn, sql, params);
        } catch (SQLException e) {
            logger.error("update entity failure");
            throw new RuntimeException(e);
        }
        return rows;
    }

    /**
     * 更新实体
     *
     * @param entityClass
     * @param id
     * @param fieldMap
     * @param <T>
     * @return
     */
    public static <T> boolean updateEntity(Class<T> entityClass, long id, Map<String, Object> fieldMap) {

        if (CollectionUtil.isEmpty(fieldMap)) {
            logger.error("can not update entity : fieldMap is empty");
            return false;
        }

        String sql = " UPDATE " + getTableName(entityClass) + " SET ";
        StringBuilder columns = new StringBuilder();
        for (String fieldName : fieldMap.keySet()) {
            columns.append(fieldName).append("=?,");
        }
        sql += columns.substring(0, columns.lastIndexOf(",")) + " WHERE ID = ?";

        List<Object> paramList = new ArrayList();
        for (Object value : fieldMap.values()) {
            paramList.add(value);
        }
        paramList.add(id);
        Object[] params = paramList.toArray();

        return excuteUpdate(sql, params) == 1;
    }

    /**
     * 插入实体
     *
     * @param entityClass
     * @param fieldMap
     * @param <T>
     * @return
     */
    public static <T> boolean insertEntity(Class<T> entityClass, Map<String, Object> fieldMap) {

        if (CollectionUtil.isEmpty(fieldMap)) {
            logger.error("can not insert entity:fieldMap is empty");
            return false;
        }

        String sql = "INSERT INTO " + getTableName(entityClass);
        StringBuilder columns = new StringBuilder("(");
        StringBuilder values = new StringBuilder("(");

        for (String fieldName : fieldMap.keySet()) {
            columns.append(fieldName).append(",");
            values.append(" ?,");
        }
        columns = columns.replace(columns.lastIndexOf(","), columns.length(), ")");
        values = values.replace(values.lastIndexOf(","), values.length(), ")");
        sql += columns + " VALUES " + values;

        Object[] params = fieldMap.values().toArray();
        return excuteUpdate(sql, params) == 1;
    }

    /**
     * 批量插入
     *
     * @param entityClass
     * @param list
     * @param <T>         要求是实体bean
     * @return
     */
    public static <T> boolean batchInsertEntity(Class<T> entityClass, List<T> list) {
        boolean result = false;

        if (CollectionUtil.isEmpty(list)) {
            logger.error("can not batch insert entity failure:list is empty");
            return result;
        }

        for (T t : list) {
            String sql = " INSERT INTO " + getTableName(entityClass);
            StringBuilder columns = new StringBuilder(")");
            StringBuilder values = new StringBuilder(")");
            List<Object> paramList = new ArrayList<>();
            Class clazz = t.getClass();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                String name = field.getName();
                String value = field.getName();
                columns.append(name).append(",");
                values.append(" ?,");
                paramList.add(value);
            }
            columns = columns.replace(columns.lastIndexOf(","), columns.length(), ")");
            values = columns.replace(values.lastIndexOf(","), values.length(), ")");
            sql = columns + "VALUES" + values;
            result = excuteUpdate(sql, paramList.toArray()) == 1;
            if (!result) {
                logger.error("batch insert entity failure：", paramList.toString());
                return result;
            }
        }
        return result;
    }

    /**
     * 删除实体
     *
     * @param entityClass
     * @param id
     * @param <T>
     * @return
     */
    public static <T> boolean deleteEntity(Class<T> entityClass, long id) {
        String sql = " DELETE  FROM " + getTableName(entityClass) + " WHERE ID = ? ";
        return excuteUpdate(sql, id) == 1;
    }

    /**
     * 通过实体获得表名
     *
     * @param entityClass
     * @param <T>
     * @return
     */
    private static <T> String getTableName(Class<T> entityClass) {
        return entityClass.getSimpleName();
    }

    /**
     * 获取数据库连接
     *
     * @return
     */
    public static Connection getConnection() {
        Connection conn = CONNECTION_HOLDER.get();
        if (conn == null) {
            try {
                conn = DATA_SOURCE.getConnection();
            } catch (SQLException e) {
                logger.error("get connection failure", e);
                throw new RuntimeException(e);
            }
        }
        return conn;
    }

    /**
     * 关闭数据库连接
     */
    @Deprecated
    public static void closeConnection() {
        Connection conn = CONNECTION_HOLDER.get();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                logger.error("close connection failure", e);
                throw new RuntimeException(e);
            } finally {
                CONNECTION_HOLDER.remove();
            }
        }
    }
}
